﻿using B.S.DataBase.MyProject.Infrastructure.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace B.S.DataBase.MyProject.Infrastructure.Implement
{

    /// <summary>
    /// 实现仓储接口
    /// </summary>
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        private readonly SDbContext db;

        public BaseRepository(SDbContext db)
        {
            this.db = db;
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> Add(T entity)
        {
            db.Set<T>().Add(entity);
            return db.SaveChanges();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> Update(T entity)
        {
           db.Set<T>().Update(entity);
           return await db.SaveChangesAsync();
        }

        /// <summary>
        /// 查询所有
        /// </summary>
        /// <returns></returns>
        public async Task<IQueryable<T>> GetAll()
        {
            return db.Set<T>();
        }


        /// <summary>
        ///批量添加
        /// </summary>
        /// <param name="entitys"></param>
        /// <returns></returns>
        public async Task<int> AddRanges(List<T> entitys)
        {
            db.Set<T>().AddRange(entitys);
            return db.SaveChanges();
        }


        /// <summary>
        /// 真删
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> DeleteRemove(List<T> entity)
        {
            db.Set<T>().RemoveRange(entity);
            return await db.SaveChangesAsync();
        }

        /// <summary>
        /// 单真删删
        /// </summary>
        /// <param name="entitys"></param>
        /// <returns></returns>
        public async Task<int> Delete(T entitys)
        {
            db.Set<T>().Remove(entitys);
            return await db.SaveChangesAsync();
        }                                                                                                                                                                                             

        /// <summary>
        /// 批量修改
        /// </summary>
        /// <param name="entitys"></param>
        /// <returns></returns>
        public async Task<int> UpdateRanhes(List<T> entitys)
        {
            db.Set<T>().UpdateRange(entitys);
            return await db.SaveChangesAsync(); 
        }

    }
}
